<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="批次" value="1"></el-option>
              <el-option label="归属" value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- 设备归属管理table -->
    <el-table stripe style="width: 100%" :data="tableData" :key="key" border fit highlight-current-row ref="tableDataRef" max-height="545">
      <el-table-column v-if="colData[0].istrue" min-width="180" align="center" prop="admin_name" label="归属"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="130" align="center" prop="batch" label="批次">
        <template slot-scope="scope">
          <el-select v-show="scope.row.batchArr.length>0" v-model="scope.row.batchArr" placeholder="请选择" multiple disabled>
            <el-option
              v-for="item in scope.row.batchNameArr"
              :key="item.id"
              :label="item.batch"
              :value="item.id.toString()">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="130" align="center" prop="startEndTime" label="开始-结束时间">
        <template slot-scope="scope">
          <div v-for="item in scope.row.startEndTime">
            <span>{{item.startTime}}</span>至
            <span>{{item.endTime}}</span>
          </div>
        </template>

      </el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="140" align="center" prop="create_time" label="创建时间">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column min-width="150" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getqueryIdTimeControl(scope.row)">编辑</el-button>
            <el-button size="mini" @click="deleteShow(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- 添加dialog表单 -->
    <el-dialog :title="editSubjects ? '平板使用时间管控' : '编辑'" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="35%">
      <el-form :model="addForm" ref="ruleForm" :rules="rules" style="padding-top:0">
        <el-form-item label="批次:" label-width="120px" prop="batch">
          <el-select v-model="addForm.batch" placeholder="没有选中任何项" class="add_select" filterable>
            <el-option v-for="item in lotoptions" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否多批时间:" label-width="120px" prop="is_times">
          <el-radio-group v-model="addForm.is_times" @change="setTimesList">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="-1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="设置管控时间段: " label-width="120px" v-show="addForm.is_times==-1">
          <div class="flex setting">
            <el-time-picker v-model="addForm.startTime" placeholder="开始时间" style="flex:1;margin-right:10px" format="HH:mm" value-format='HH:mm'></el-time-picker>
            <el-time-picker v-model="addForm.endTime" placeholder="结束时间" style="flex:1" format="HH:mm" value-format='HH:mm'></el-time-picker>
          </div>
        </el-form-item>

        <div v-for="(item,index) in timesList" >
            <el-form-item  label-width="10px" v-show="addForm.is_times==1">
              <div class="flex setting">
                <el-time-picker v-model="item.startTime" placeholder="开始时间" style="flex:1;margin-right:10px" format="HH:mm" value-format='HH:mm'></el-time-picker>
                <el-time-picker v-model="item.endTime" placeholder="结束时间" style="flex:1" format="HH:mm" value-format='HH:mm'></el-time-picker>
                <el-button icon="el-icon-plus" type="primary" size="mini" @click="toAddList"></el-button>
                <el-button icon="el-icon-minus" type="danger" size="mini" @click="toRemoveList(item,index)"></el-button>
              </div>
            </el-form-item>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" @click="getaddTimeControl('ruleForm')" size="mini" round>确 定</el-button>
        <el-button v-else type="primary" @click="geteditTimeControl('ruleForm')" size="mini" round>编辑</el-button>
      </div>
    </el-dialog>
    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import deleteDialog from "@/components/deleteDialog";
import { queryTimeControl, addTimeControl, deleteTimeControl, queryIdTimeControl, editTimeControl } from "@/api/deployment.js";
import { getBatchTwo } from "@/api/equipment.js";
import tableMini from '@/utils/tableMini.js'
export default {
  mixins: [tableMini],
  components: { dynamicTable, deleteDialog },
  data() {
    return {
      checkboxVal: ["归属", "批次", "开始-结束时间", "创建时间"],
      tableData: [],
      select: "1", //搜索条件
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), batch: undefined, username: undefined },
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制
      editSubjects: true,
      //浏览器专题id
      subjectId: 0,
      //家长SN码下拉选择
      lotoptions: [],
      //添加表单
      addForm: { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), batch: "", startTime: "", endTime: "", is_times: -1,times:[] },
      rules: { batch: [{ required: true, message: "请选择批次", trigger: "blur" }]},
      timesList: [{
        startTime: '',
        endTime: '',
      }]
    }
  },
  created() {
    this.getTabularData()
    this.getBatchTwos()
  },
  methods: {
    getTabularData() {
      queryTimeControl(this.listQuery).then(res => {
        this.tableData = res.data
        this.total = res.total
      }).catch(err => {
        this.tableData = []
        this.total = 0
      })
    },
    //删除按钮事件
    deleteEvents() {
      let params = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), id: this.deleteDialogs.deleteId }
      deleteTimeControl(params).then(res => {
        this.$message.success(res.msg)
        this.getTabularData()
      })
    },
    //添加按钮事件
    btnaddBrand() {
      this.editSubjects = true
      this.dialogFormVisible = true
    },
    //增加时间管控
    getaddTimeControl(formName) {
      if(this.checkTimesList()) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let addForm = JSON.parse(JSON.stringify(this.addForm))
            addForm.batch = this.addForm.batch
            addForm.times = JSON.parse(JSON.stringify(this.timesList))
            addTimeControl(addForm).then(res => {
              this.$message.success(res.msg)
              this.getTabularData()
              this.dialogFormVisible = false
            }).catch(err => {
            })
          } else {
            return false
          }
        })
      }
    },
    //编辑
    geteditTimeControl(formName) {
      if(this.checkTimesList()) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let addForm = JSON.parse(JSON.stringify(this.addForm))
            addForm.batch = this.addForm.batch
            addForm.id = this.subjectId
            addForm.times = JSON.parse(JSON.stringify(this.timesList))
            editTimeControl(addForm).then(res => {
              this.dialogFormVisible = false
              this.$message.success(res.msg)
              this.getTabularData()
            }).catch(err => {
            })
          } else {
            return false
          }
        })
      }
    },
    //根据ID查询信息
    getqueryIdTimeControl(row) {
      this.editSubjects=false
      this.dialogFormVisible=true
      this.timesList = row.timesList;
      this.addForm = {
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        batch: row.batch,
        startTime: row.start_time,
        endTime: row.end_time,
        is_times: row.is_times,
      }
      this.subjectId = row.id

    },
    //根据ID获取批次列表
    getBatchTwos() {
      let data = { userId: localStorage.getItem("ID") }
      getBatchTwo(data).then(res => {
        this.lotoptions = res.data
      }).catch(err => {
        this.lotoptions = []
      })
    },
    //搜索,1:网址，2:类型
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          let search = this.lotoptions.filter(key => key.batch == this.searchTable).map(item => item.id)[0]
          this.listQuery.batch = search ? search : this.searchTable
          this.getTabularData();
          break;
        case '2':
          this.listQuery.username = this.searchTable
          this.getTabularData();
          break;
      }
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.addForm = this.$options.data().addForm
        this.timesList = this.$options.data().timesList
      })
    },
    toAddList() {
      this.timesList.push({
        startTime: '',
        endTime: ''
      })
    },
    toRemoveList(item,index){
      if (this.timesList.length == 1) {
        this.$message.error('请至少添加一批管控时间~')
        return
      }
      let tempList = this.timesList
      tempList.map((value, i) => {
        if ( i== index) {
          tempList.splice(index, 1);
          this.timesList = tempList;
        }
      });
    },
    setTimesList() {
      if(this.timesList.length == 0) {
        this.timesList.push({
          startTime: '',
          endTime: '',
        })
      }
    },
    checkTimesList() {
      let flag = true
      let msg = ''
      if(this.timesList.length >= 1 && this.addForm.is_times==1) {
        this.timesList.forEach((item,index) => {
          if(item.startTime >= item.endTime) {
            var num = index+1
            msg += '第'+num+'项的开始时间大于结束时间'
            flag = false
            this.$message.error(msg)
          }
        })
      }
      return flag
    },
  }
}
</script>
